// import { name } from '@vue/eslint-config-prettier/skip-formatting'
import { defineStore } from 'pinia'
import { ref } from 'vue'
import axios from 'axios'
export const useMenuStore = defineStore('menu', () => {
  const menuList = ref([])
  const currentMenu = ref(null)
  const collapsed = ref(false)
  const token = ref(sessionStorage.getItem('token') || localStorage.getItem('token'));
  const pagination = ref({
    page: 1,
    pageSize: 10,
    total: 0
  });
  const MenusList =ref([])
  const menus = ref([])
  const setMenuList = (menus) => {
    menuList.value = menus
  }

  const loadMenuList = async () => {
    try {
      // 模拟菜单数据，基于数据库结构
      const mockMenus = [
        {
          id: 1,
          name: '仪表盘',
          path: '/dashboard',
          icon: 'Odometer',
          children: []
        },
        {
          id: 2,
          name: '用户管理',
          path: '/users',
          icon: 'User',
          children: [
            {
              id: 7,
              name: '用户列表',
              path: '/users/list',
              icon: 'List'
            },
            {
              id: 8,
              name: '添加用户',
              path: '/users/add',
              icon: 'Plus'
            }
          ]
        },
        {
          id: 3,
          name: '角色管理',
          path: '/roles',
          icon: 'Lock',
          children: [
            {
              id: 9,
              name: '角色列表',
              path: '/roles/list',
              icon: 'Role'
            },
            {
              id: 10,
              name: '添加角色',
              path: '/roles/add',
              icon: 'Plus'
            }
          ]
        },
        {
          id: 4,
          name: '菜单管理',
          path: '/menus',
          icon: 'Menu',
          children: [
            {
              id: 11,
              name: '菜单列表',
              path: '/menus/list',
              icon: 'List'
            },
            {
              id: 12,
              name: '添加菜单',
              path: '/menus/add',
              icon: 'Plus'
            }
          ]
        },
        {
          id: 5,
          name: '系统设置',
          path: '/system',
          icon: 'Setting',
          children: [
            {
              id: 13,
              name: '系统配置',
              path: '/system/config',
              icon: 'Tools'
            }
          ]
        },
        {
          id: 6,
          name: '日志管理',
          path: '/logs',
          icon: 'Document',
          children: [
            {
              id: 14,
              name: '操作日志',
              path: '/logs/operation',
              icon: 'Document'
            }
          ]
        },
        {
          id: 15,
          name: '内容管理',
          path: '/content',
          icon: 'Memo',
          children: [
            {
              id: 17,
              name: '文章管理',
              path: '/content/article',
              icon: 'Document'
            },
            {
              id: 16,
              name: '文件管理',
              icon: 'Files',
              path: '/content/filemanage'
            }
          ]
        }
      ]

      setMenuList(mockMenus)
      return mockMenus
    } catch (error) {
      console.error('加载菜单失败:', error)
      return []
    }
  }

  const setCurrentMenu = (menu) => {
    currentMenu.value = menu
  }

  const toggleCollapse = () => {
    collapsed.value = !collapsed.value
  }
  //获取菜单列表
  const getMenu = async () => {
    try {
      const response = await axios.get('/api/menus', {
        headers: {
          'Authorization': `Bearer ${token.value}`
        },
        params: {
          page: pagination.value.page,
          pageSize: pagination.value.pageSize
        }
      });
      const { items, totalCount, pageIndex, pageSize } = response.data.data;
      menus.value = items; 
      pagination.value = {
        page: pageIndex,
        pageSize: pageSize,
        total: totalCount
      }; 
      return { menus: menus.value, pagination: pagination.value }
    } catch (error) {
      throw new Error(error.response?.data?.message || 'fetch_menus_failed');
    }
  }
  //添加菜单行
  const addMenu = async (menu) => {
    try {
      const response = await axios.post('/api/menus', menu,{
        headers: {
          'Authorization': `Bearer ${token.value}`
        }
      });
      return response.data.data;
    } catch (error) {
      throw new Error(error.response?.data?.message || 'post_menus_failed');
    }
  }
  //编辑菜单行
  const updateMenu=async (menuId,menu) => {
    try {
      const response = await axios.put(`/api/menus/${menuId}`, menu,{
        headers: {
          'Authorization': `Bearer ${token.value}`
        }
      });
      return response.data.data;
    } catch (error) {
      throw new Error(error.response?.data?.message || 'post_menus_failed');
    }
  }
  //删除菜单行
  const deleteMenu =async (menuId) => {
    try {
      const response = await axios.delete(`/api/menus/${menuId}`,{
        headers: {
          'Authorization': `Bearer ${token.value}`
        }
      });
      return response.data.data;
    } catch (error) {
      throw new Error(error.response?.data?.message || 'post_menus_failed');
    }
  }
  //获取菜单树
  const getmenutree =async()=>{
      try {
      const response = await axios.get(`/api/menus/tree`,{
        headers: {
          'Authorization': `Bearer ${token.value}`
        }
      });
      return response.data.data;
    } catch (error) {
      throw new Error(error.response?.data?.message || 'post_menus_failed');
    }
  }
  //菜单搜索查询实现
  const fetchMenu =async()=>{
try {
      const response = await axios.get('/api/menus', {
        headers: { 'Authorization': `Bearer ${token.value}` },
        params: {
          keyword: searchForm.keyword || undefined, // 如果为空则不传
          page: pagination.value.page,
          pageSize: pagination.value.pageSize
        },
      })
      const { items, totalCount, pageIndex, pageSize } = response.data.data;
      MenusList.value = items;
      pagination.value = {
        page: pageIndex,
        pageSize: pageSize,
        total: totalCount
      };
      return { MenusList: MenusList.value, pagination: pagination.value }
    } catch (error) {
      ElMessage.error('获取用户列表失败')
      console.error(error)
    }
  }
  return {
    menuList,
    currentMenu,
    collapsed,
    setMenuList,
    loadMenuList,
    setCurrentMenu,
    toggleCollapse,
    getMenu,
    addMenu,
    updateMenu,
    deleteMenu,
    getmenutree,
    fetchMenu
  }
})